//依赖
const gulp = require("gulp");
const concat = require("gulp-concat");
const uglify = require("gulp-uglify");
const cleanCss = require("gulp-clean-css");
var sass = require('gulp-sass');
sass.compiler = require('node-sass');

const findSync = require("./utils/index").findSync;
const scssJSON  = require("./conf/index").scss;
const scripts  = require("./conf/index").scripts;

let scriptsPathArray = null;
let scriptsTaskArray = [];
let scssTaskArray = [];


//路径配置 获取当前路径下所有文件路径
function init(){
    let scriptsPathArr = findSync('./src/scripts').map(item=>{
        return './' + item.replace(/\\/g,'/');
     });
    const scriptsUnSaveArray = ["!./src/scripts/libs/*.js"];
    scriptsPathArr = scriptsPathArr.concat(scriptsUnSaveArray);
    mergeMyScripts(scripts)
    mergeMyScss(scssJSON)
}

//监听js改变
function watchScripts(json){
    for(let attr in json){
        gulp.watch(json[attr].src+'*.js',['scripts-' + attr]);
    }
}

function watchScss(json){
    for(let attr in json){
          gulp.watch(json[attr].src+"*.scss",["scss-"+attr])
    }
}

//分src合并js
function mergeMyScripts(json){
    for(let attr in json){
        scriptsTaskArray.push("scripts-build-"+attr)
        gulp.task('scripts-build-'+attr,()=>{
            return  gulp.src([scripts[attr].src+"*.js"])
            .pipe(concat(attr + '.js'))
            .pipe(uglify())
            .pipe(gulp.dest('./dev/scripts'))
        })
    }
}

function mergeMyScss(json){
    for(let attr in json){
        scssTaskArray.push("scss-build-"+attr)
        gulp.task('scss-build-'+attr,()=>{
            return  gulp.src([json[attr].src+"*.scss"])
            .pipe(concat(attr + '.scss'))
            .pipe(sass().on('error',sass.logError))
            .pipe(cleanCss({debug: true}, (details) => {
                console.log(`${details.name}: ${details.stats.originalSize}`);
                console.log(`${details.name}: ${details.stats.minifiedSize}`);
              }))
            .pipe(gulp.dest('./dev/stylesheets'))
        })
    }
}



//转存html
gulp.task('html-build',()=>{
    return gulp.src(['./src/*.html'])
    .pipe(gulp.dest('./dev'))
})


//总合并js
gulp.task('scripts-build',scriptsTaskArray)
//总合并scss
gulp.task('scss-build',scssTaskArray)

//启动服务器

gulp.task("build",["html-build",'scripts-build','scss-build'])


init() 